package com.netease.nim.uikit.session.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dididoctor.patient.Bean.DiaeasesLitapal;
import com.netease.nim.uikit.R;
import com.netease.nim.uikit.common.fragment.TFragment;
import com.netease.nim.uikit.session.SessionCustomization;
import com.netease.nim.uikit.session.actions.BaseAction;
import com.netease.nim.uikit.session.actions.ImageAction;
import com.netease.nim.uikit.session.actions.ImageBasePresenter;
import com.netease.nim.uikit.session.constant.Extras;
import com.netease.nim.uikit.session.constant.RequestCode;
import com.netease.nim.uikit.session.module.Container;
import com.netease.nim.uikit.session.module.ModuleProxy;
import com.netease.nim.uikit.session.module.input.InputPanel;
import com.netease.nim.uikit.session.module.list.MessageListPanel;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomMessageConfig;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.MessageReceipt;

import java.util.ArrayList;
import java.util.List;

/**
 * 聊天界面基类
 * <p/>
 * Created by huangjun on 2015/2/1.
 */
public class MessageFragment extends TFragment implements ModuleProxy {

    private View rootView;

    private SessionCustomization customization;

    protected static final String TAG = "MessageActivity";

    // 聊天对象
    protected String sessionId; // p2p对方Account或者群id

    protected SessionTypeEnum sessionType;

    // modules
    protected InputPanel inputPanel;
    protected MessageListPanel messageListPanel;
    private TextView tv_title, tv_finish;
    private LinearLayout messageActivityLayout;
    private RelativeLayout messageActivityLayoutGoToRefer, textMessageLayout;//继续咨询和聊天底部
    private boolean isgo = false;
    private String hosId, recId, doctorId, status, userid, token, accId, rank, name, sign;
    private Button btn_confirm_gotorefer;
    private List<DiaeasesLitapal> litapals;
    private ImageBasePresenter presenter;

    public MessageFragment() {
        super();
    }

    //recid问诊表表的ID   disid疾病的id
    @SuppressLint("ValidFragment")
//    start,recid,hosId,userid,token    //doctorid 医院的ID    accId 聊天人的云信ID
    public MessageFragment(ImageBasePresenter presenter, String start, String recid, String hosId, String userid, String token, String doctorid, String accId, String name, String sign) {
        super();
        this.status = start;
        this.recId = recid;
        this.hosId = hosId;
        this.userid = userid;
        this.token = token;
        this.doctorId = doctorid;
        this.accId = accId;
        this.name = name;
        this.presenter = presenter;
        this.sign = sign;
    }

    @SuppressLint("WrongViewCast")
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        parseIntent();

//        /***********广播*****************/
//        initBroadcast();

        tv_title = (TextView) rootView.findViewById(R.id.tv_title);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText(name);
        tv_finish = (TextView) rootView.findViewById(R.id.tv_finish);
        messageActivityLayout = (LinearLayout) rootView.findViewById(R.id.messageActivityLayout);

        textMessageLayout = (RelativeLayout) rootView.findViewById(R.id.textMessageLayout);
        textMessageLayout.setVisibility(View.VISIBLE);
        messageActivityLayoutGoToRefer = (RelativeLayout) rootView.findViewById(R.id.textMessageLayout_goto_refer);
        messageActivityLayoutGoToRefer.setVisibility(View.GONE);
        tv_finish.setVisibility(View.VISIBLE);
        btn_confirm_gotorefer = (Button) rootView.findViewById(R.id.btn_confirm_gotorefer);


        if ("2".equals(status)) {
            isgo = true;
            if (isgo) {
                Intent intent = new Intent();
                intent.setAction("com.getP2PMessage");
                intent.putExtra("msgType", "TWOEND");
                intent.putExtra("hosId", hosId);
                intent.putExtra("recId", recId);
                intent.putExtra("userid", userid);
                intent.putExtra("token", token);
                //doctorid 医院的ID    accId 聊天人的云信ID
                intent.putExtra("doctorid", doctorId);
                intent.putExtra("accId", accId);
                intent.putExtra("name", name);
                intent.putExtra("sign", sign);
                rootView.getContext().sendBroadcast(intent);
                textMessageLayout.setVisibility(View.GONE);
                messageActivityLayoutGoToRefer.setVisibility(View.GONE);
                tv_finish.setVisibility(View.GONE);
                isgo = false;
            }
        } else if ("4".equals(status)) {
            textMessageLayout.setVisibility(View.GONE);
            messageActivityLayoutGoToRefer.setVisibility(View.VISIBLE);
            tv_finish.setVisibility(View.GONE);
        } else {
            textMessageLayout.setVisibility(View.VISIBLE);
            messageActivityLayoutGoToRefer.setVisibility(View.GONE);
        }

        tv_finish.setText("结束咨询");
        tv_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IMMessage msg = MessageBuilder.createTipMessage(sessionId, sessionType);
                msg.setContent("结束会话");

                CustomMessageConfig config = new CustomMessageConfig();
                config.enablePush = true; // 不推送
                msg.setConfig(config);

                sendMessage(msg);
                isgo = true;
                if (isgo) {
                    Intent intent = new Intent();
                    intent.setAction("com.getP2PMessage");
                    intent.putExtra("msgType", "END");
                    intent.putExtra("hosId", hosId);
                    intent.putExtra("recId", recId);
                    intent.putExtra("userid", userid);
                    intent.putExtra("token", token);
                    //doctorid 医院的ID    accId 聊天人的云信ID
                    intent.putExtra("doctorid", doctorId);
                    intent.putExtra("accId", accId);
                    intent.putExtra("name", name);
                    intent.putExtra("sign", sign);
                    rootView.getContext().sendBroadcast(intent);

                    textMessageLayout.setVisibility(View.GONE);
                    messageActivityLayoutGoToRefer.setVisibility(View.GONE);
                    tv_finish.setVisibility(View.GONE);
                    isgo = false;
                }
            }
        });

        //立即咨询
        btn_confirm_gotorefer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isgo = true;
                if (isgo) {
                    Intent intent = new Intent();
                    intent.setAction("com.getP2PMessage");
                    intent.putExtra("msgType", "CONSULT");
                    intent.putExtra("hosId", hosId);
                    intent.putExtra("recId", recId);
                    intent.putExtra("userid", userid);
                    intent.putExtra("token", token);
                    //doctorid 医院的ID    accId 聊天人的云信ID
                    intent.putExtra("doctorid", doctorId);
                    intent.putExtra("accId", accId);
                    intent.putExtra("name", name);
                    intent.putExtra("sign", sign);

                    rootView.getContext().sendBroadcast(intent);
                    textMessageLayout.setVisibility(View.GONE);
                    messageActivityLayoutGoToRefer.setVisibility(View.VISIBLE);
                    isgo = false;
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.nim_message_fragment, container, false);

        return rootView;
    }


    /**
     * ***************************** life cycle *******************************
     */

    @Override
    public void onPause() {
        super.onPause();

        NIMClient.getService(MsgService.class).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_NONE,
                SessionTypeEnum.None);
        inputPanel.onPause();
        messageListPanel.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        messageListPanel.onResume();
        NIMClient.getService(MsgService.class).setChattingAccount(sessionId, sessionType);
        getActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL); // 默认使用听筒播放
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        messageListPanel.onDestroy();
        registerObservers(false);
    }

    public boolean onBackPressed() {
        if (inputPanel.collapse(true)) {
            return true;
        }

        if (messageListPanel.onBackPressed()) {
            return true;
        }
        return false;
    }

    public void refreshMessageList() {
        messageListPanel.refreshMessageList();
    }

    private void parseIntent() {
        sessionId = getArguments().getString(Extras.EXTRA_ACCOUNT);
        sessionType = (SessionTypeEnum) getArguments().getSerializable(Extras.EXTRA_TYPE);

        customization = (SessionCustomization) getArguments().getSerializable(Extras.EXTRA_CUSTOMIZATION);
        Container container = new Container(getActivity(), sessionId, sessionType, this);

        if (messageListPanel == null) {
            messageListPanel = new MessageListPanel(container, rootView, false, false);
        } else {
            messageListPanel.reload(container, null);
        }

        if (inputPanel == null) {
            inputPanel = new InputPanel(container, rootView, getActionList());
            inputPanel.setCustomization(customization);
        } else {
            inputPanel.reload(container, customization);
        }

        registerObservers(true);

        if (customization != null) {
            messageListPanel.setChattingBackground(customization.backgroundUri, customization.backgroundColor);
        }
    }

    /**
     * ************************* 消息收发 **********************************
     */
    // 是否允许发送消息
    protected boolean isAllowSendMessage(final IMMessage message) {
        return true;
    }

    /**
     * ****************** 观察者 **********************
     */

    private void registerObservers(boolean register) {
        MsgServiceObserve service = NIMClient.getService(MsgServiceObserve.class);
        service.observeReceiveMessage(incomingMessageObserver, register);
        service.observeMessageReceipt(messageReceiptObserver, register);
    }

    /**
     * 消息接收观察者
     */
    Observer<List<IMMessage>> incomingMessageObserver = new Observer<List<IMMessage>>() {
        @Override
        public void onEvent(List<IMMessage> messages) {
            if (messages == null || messages.isEmpty()) {
                return;
            }

            messageListPanel.onIncomingMessage(messages);
            sendMsgReceipt(); // 发送已读回执
        }
    };

    private Observer<List<MessageReceipt>> messageReceiptObserver = new Observer<List<MessageReceipt>>() {
        @Override
        public void onEvent(List<MessageReceipt> messageReceipts) {
            receiveReceipt();
        }
    };


    /**
     * ********************** implements ModuleProxy *********************
     */
    @Override
    public boolean sendMessage(IMMessage message) {
        if (!isAllowSendMessage(message)) {
            return false;
        }

        // send message to server and save to db
        NIMClient.getService(MsgService.class).sendMessage(message, false);

        messageListPanel.onMsgSend(message);

        return true;
    }

    @Override
    public void onInputPanelExpand() {
        messageListPanel.scrollToBottom();
    }

    @Override
    public void shouldCollapseInputPanel() {
        inputPanel.collapse(false);
    }

    @Override
    public boolean isLongClickEnabled() {
        return !inputPanel.isRecording();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        inputPanel.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 111) {
            textMessageLayout.setVisibility(View.VISIBLE);
            messageActivityLayoutGoToRefer.setVisibility(View.GONE);
        }
    }

    // 操作面板集合
    protected List<BaseAction> getActionList() {
        List<BaseAction> actions = new ArrayList<>();
        actions.add(new ImageAction(presenter, RequestCode.PICK_IMAGE));
        actions.add(new ImageAction(presenter, RequestCode.PREVIEW_IMAGE_FROM_CAMERA));
//        actions.add(new VideoAction());
//        actions.add(new LocationAction());

        if (customization != null && customization.actions != null) {
            actions.addAll(customization.actions);
        }
        return actions;
    }

    /**
     * 发送已读回执
     */
    private void sendMsgReceipt() {
        messageListPanel.sendReceipt();
    }

    /**
     * 收到已读回执
     */
    public void receiveReceipt() {
        messageListPanel.receiveReceipt();
    }


    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("Baseaction")) {
                getYearMD();
            }
        }
    }
    /**********************************************
     * 日期滚轴后期封装
     *****************************************************/
    /**
     * 初始化广播
     */
    private void initBroadcast() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("Baseaction");
        mMyBroadcastReceiver = new MyBroadcastReceiver();
        //消息红点
        rootView.getContext().registerReceiver(mMyBroadcastReceiver, intentFilter);
    }

    private PopupWindow pw;
    //选择时间与当前时间，用于判断用户选择的是否是以前的时间
    private int currentHour, currentMinute, currentDay, selectHour, selectMinute, selectDay;
    private MyBroadcastReceiver mMyBroadcastReceiver;

    protected void getYearMD() {
        View view = View.inflate(rootView.getContext(), R.layout.topbar_mine, null);
        //设置滑动改变监听器
        pw = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        //出现在布局底端
        pw.showAtLocation(messageActivityLayout, 0, 0, Gravity.END);
    }
}
